package meijuli.com.join51.business.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import meijuli.com.join51.business.R;
import meijuli.com.join51.business.aliyun.AliyunOSS;
import meijuli.com.join51.business.aliyun.UploadListener;
import meijuli.com.join51.business.aliyun.ImageUtils;
import com.jhx.common.widget.CommonDialog;
import meijuli.com.join51.business.ui.ListDialog;
import meijuli.com.join51.business.utils.PermissionUtils;
import com.jhx.common.utils.ToastUtil;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 包含上传图片的Fragment
 *
 * @author wenqin 2017-05-23 09:42
 */
public abstract class PhotoFragment extends BaseFragment implements ImageUtils.SelectImageListener,
        EasyPermissions.PermissionCallbacks {
    /**
     * 从相册中选择照片回调
     */
    protected static final int REQUEST_CODE_CAPTURE = 6;
    protected static final int REQUEST_CODE_ALBUM = 7;
    /**
     * 点击哪张图片，左边为1，右边为2 ，因为有些页面只有一张，所以默认为TYPE_PIC_1
     */
    protected static final int TYPE_PIC_1 = 1;
    protected static final int TYPE_PIC_2 = 2;
    protected static boolean setPermissions = false;
    protected int toType = TYPE_PIC_1;
    protected String mPicPath1, mPicPath2;
    protected String mLocalPicPath1, mLocalPicPath2;

    private OnUploadSuccess mOnUploadSuccess = new OnUploadSuccess() {
        @Override
        public void uploadSuccess(String cloudKey, String sourceFilePath) {
            onUpLoadSuccess(cloudKey, sourceFilePath);
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        AliyunOSS.get().init();
    }

    /**
     * 上传成功
     *
     * @param cloudKey  返回的url
     * @param sourceFilePath 文件本地地址
     */
    protected abstract void onUpLoadSuccess(String cloudKey, String sourceFilePath);

    protected void showListDialog() {
        ListDialog.showDialog(getActivity(),
                getResources().getStringArray(R.array.dialog_list_photos),
                new ListDialog.OnListItemClickListener() {
                    @Override
                    public void listItemClick(int position) {
                        if (position == 0) {
                            toCameraGo();
                        } else if (position == 1) {
                            ImageUtils.get().openGalleryForResult(PhotoFragment.this,
                                    REQUEST_CODE_ALBUM);
                        }
                    }
                });

    }

    public void toCameraGo() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            ImageUtils.get().capturePhoto(this, REQUEST_CODE_CAPTURE);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CommonDialog dialog = new CommonDialog(getActivity());
                dialog.setMessage("为了保证聚惠侠商家版可以正常使用,请在设置-应用-聚惠侠商家版-权限，开启拍照权限");
                dialog.setConfirmBtn("设置");
                dialog.show();
                dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onConfirmClick(View view) {
                        setPermissions = true;
                        PermissionUtils.getInstance().toSetting(getActivity());
                    }

                    @Override
                    public void onCancelClick(View view) {
                        ToastUtil.getInstance().showToast("拍照权限被拒绝");
                    }
                });
            }else {
                EasyPermissions.requestPermissions(this, "应用需要获取拍照权限，请授权",
                        REQUEST_CODE_CAPTURE, Manifest.permission.CAMERA);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(setPermissions) {
            checkPermissions();
        }
    }

    public void checkPermissions() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            setPermissions = false;
            ImageUtils.get().capturePhoto(this, REQUEST_CODE_CAPTURE);
        } else {
            ToastUtil.getInstance().showToast("拍照权限已拒绝");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        ImageUtils.get().capturePhoto(this, REQUEST_CODE_CAPTURE);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.CAMERA);
        checkPermission(permissionList, "该功能需要使用您的相机，请前往设置-权限管理，开启拍照权限");
    }

    @Override
    public void onSelectDone() {
        try {
            File tempFile1 = ImageUtils.get().getImageFile();
            if (tempFile1 == null || !tempFile1.exists() || tempFile1.length() == 0) {
                CrashReport.postCatchedException(new RuntimeException("所选文件为空"));
                ToastUtil.getInstance().showToast(getActivity(), "获取图片失败, 请重试!");
                return;
            }
            Luban.with(getActivity())
                    .load(tempFile1)
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            showLoadingDialog();
                        }

                        @Override
                        public void onSuccess(File file) {
                            dismissDialog();
                            String tempPath = file.getPath();
                            if (!TextUtils.isEmpty(tempPath)) {
                                uploadHeadImage(tempPath);
                            } else {
                                ToastUtil.getInstance().showToast("压缩图片失败，请重试");
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            dismissDialog();
                            ToastUtil.getInstance().showToast("压缩图片失败，请重试");
                            e.printStackTrace();
                            CrashReport.postCatchedException(e);
                        }
                    }).launch();
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
        }
    }

    @Override
    public void onSelectFail() {
        ToastUtil.getInstance().showToast(getActivity(), R.string.image_format_fail);
    }



    private void uploadHeadImage(final String picPath) {
        showLoadingDialog("上传中...");
        try {
            AliyunOSS.get().upload(picPath, new UploadListener() {

                @Override
                public void onSuccess(String cloudKey, String sourceFilePath) {
                    dismissDialog();
                    ToastUtil.getInstance().showToast(getActivity(), "上传成功");
                    if (toType == TYPE_PIC_1) {
                        mPicPath1 = cloudKey;
                        mLocalPicPath1 = sourceFilePath;
                    }
                    if (toType == TYPE_PIC_2) {
                        mPicPath2 = cloudKey;
                        mLocalPicPath2 = sourceFilePath;
                    }
                    if (mOnUploadSuccess != null) {
                        mOnUploadSuccess.uploadSuccess(cloudKey, sourceFilePath);
                    }
                }

                @Override
                public void onProgress(String cloudKey, long progress, long total) {

                }

                @Override
                public void onFailure(String cloudKey, ClientException exception) {
                    dismissDialog();
                    resetPicKey();
                    ToastUtil.getInstance().showToast(getActivity(), "图像上传失败", Toast.LENGTH_SHORT);
                }
            });
        } catch (FileNotFoundException e) {
            dismissDialog();
            resetPicKey();
            ToastUtil.getInstance().showToast(getActivity(), "图像上传失败", Toast.LENGTH_SHORT);
        }
    }

    private void resetPicKey() {
        if (toType == TYPE_PIC_1) {
            mPicPath1 = "";
        } else {
            mPicPath2 = "";
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAPTURE:
                    onSelectDone();
                    break;
                case REQUEST_CODE_ALBUM:
                    if (data == null) {
                        return;
                    }
                    ImageUtils.get().galleryImage(this, data.getData(), this);
                    break;
                default:

                    break;
            }
        }
    }

    interface OnUploadSuccess {
        void uploadSuccess(String cloudKey, String sourceFilePath);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        AliyunOSS.get().recycler();
    }
}
